package com.f6.common.service;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.f6.common.util.HttpUtil;
import com.f6.common.util.JsonUtil;
import com.f6.model.AppStation;
import com.f6.model.Fenxiang;
import com.f6.model.Puser;
import com.google.gson.Gson;

import common.weixinutils.response.Article;

/**
 * @author songpeng
 * @date 2014年5月14日
 **/

public class CommonService {

	public static List getList(String Url) {
		List list = null;

		// 查询并解析结果
		try {
			// 查询并获取返回结果
			String json = HttpUtil.httpRequest(Url);
			// 通过Gson工具将json转换成TranslateResult对象
			list = new Gson().fromJson(json, List.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	public static List<Article> getArticlesByList(List list, String openId) {
		List<Article> articleList = null;
		if (list != null) {
			articleList = new ArrayList<Article>();
			Article article = null;
			for (int i = 0; i < list.size(); i++) {
				if (i == 10) {
					break;
				}
				Map map = (Map) list.get(i);
				article = new Article();
				article.setTitle((String) map.get("Title"));
				article.setDescription((String) map.get("Description"));
				article.setPicUrl((String) map.get("PicUrl"));
				if (openId != null) {
					article.setUrl((String) map.get("Url") + "&openId="
							+ openId);
				} else {
					article.setUrl((String) map.get("Url"));
				}

				if (!articleList.contains(article)) {
					articleList.add(article);
				}
			}
		}
		return articleList;
	}

	public static String getToken(String appid, String appsecret) {
		String url = "http://api.f6car.com/datasrv/2.0/weixin/weixintoken?";
		String token = "";
		String param = "param={\"businessCode\": \"f60001\", \"params\": "
				+ "{\"appid\":\"" + appid + "\",\"appsecret\":\"" + appsecret
				+ "\"}}";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				JSONObject detailObject = jsonObject.getJSONObject("detail");
				if (detailObject != null) {
					try {
						token = detailObject.getString("token");
					} catch (Exception ex) {
						// do nothing
						token = "";
					}
				}
			}
		}
		return token;
	}
	
	public static AppStation getAppStation(String appid, String wxAppSid) {
		AppStation appStation = null;
		Connection con= DBUtil.getConn();
		Statement st = null;
		ResultSet rs = null;
		try {
			String sql="select * from p_app_station where WX_APP_ID='"+appid+"'";
			st = con.createStatement();
			rs = st.executeQuery(sql);
			if(rs.next()){
				appStation= new AppStation();
				appStation.setAppName(rs.getString("WX_APP_NAME"));
				appStation.setToken(rs.getString("TOKEN"));
				appStation.setWxAppId(rs.getString("WX_APP_ID"));
				appStation.setWxAppSid(rs.getString("WX_APP_SID"));
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}finally{
			try {
				rs.close();
				st.close();
				con.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		return appStation;
	}
	
	/*public static AppStation getAppStation(String appid, String wxAppSid) {
		String url = "http://api.f6car.com/datasrv/2.0/weixin/appstation?";
		String param = "";
		if (appid != null) {
			param = "param={\"businessCode\": \"f60002\", \"params\": "
					+ "{\"appid\":\"" + appid + "\"}}";
		}
		if (wxAppSid != null) {
			param = "param={\"businessCode\": \"f60002\", \"params\": "
					+ "{\"wxAppSid\":\"" + wxAppSid + "\"}}";
		}
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		AppStation appStation = null;
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				appStation = new AppStation();
				JSONObject detailObject = jsonObject.getJSONObject("detail");
				if (detailObject != null) {
					try {
						String token = detailObject.getString("token");
						appStation.setToken(token);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						String wxAppName = detailObject.getString("wxAppName");
						appStation.setAppName(wxAppName);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						wxAppSid = detailObject.getString("wxAppSid");
						appStation.setWxAppSid(wxAppSid);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						appid = detailObject.getString("wxAppId");
						appStation.setWxAppId(appid);
					} catch (Exception ex) {
						// do nothing
					}
				}
			}
		}
		return appStation;
	}*/

	public static Puser getPuserById(String userId) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/getpuserById?";
		String token = "";
		String param = "param={\"businessCode\": \"f60003\", \"params\": "
				+ "{\"userId\":\"" + userId + "\"}}";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		Puser puser = null;
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				JSONObject detailObject = jsonObject.getJSONObject("detail");
				if (detailObject != null) {
					puser = new Puser();
					puser.setUserId(userId);
					try {
						String userName = detailObject.getString("userName");
						puser.setUserName(userName);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						String nickName = detailObject.getString("nickName");
						puser.setNickName(nickName);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						String wxOpenId = detailObject.getString("wxOpenId");
						puser.setWxOpenId(wxOpenId);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						String wxAppId = detailObject.getString("wxAppId");
						puser.setWxAppId(wxAppId);
					} catch (Exception ex) {
						// do nothing
					}
				}
			}
		}
		return puser;
	}

	public static String getappsercet(String appid) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/appsecret?";
		String appSecret = "";
		String param = "param={\"businessCode\": \"pengsong001\", \"params\": "
				+ "{\"appid\":\"" + appid + "\"}}";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				JSONObject detailObject = jsonObject.getJSONObject("detail");
				if (detailObject != null) {
					try {
						appSecret = detailObject.getString("appSecret");
					} catch (Exception ex) {
						// do nothing
						appSecret = "";
					}
				}
			}
		}
		return appSecret;
	}

	public static boolean judgePuser(String wxAppId, String wxOpenId) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/judgePuser?";
		boolean judge = false;
		String param = "param={\"businessCode\": \"f60007\", \"params\": "
				+ "{\"wxAppId\":\"" + wxAppId + "\",\"wxOpenId\":\"" + wxOpenId
				+ "\"}}";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				try {
					String judgeStr = jsonObject.getString("detail");
					if ("1".equals(judgeStr)) {
						judge = true;
					}
				} catch (Exception ex) {
					// do nothing
					judge = false;
				}
			}
		}
		return judge;
	}

	public static Integer savePuserForId(String userName, String nickName,
			String openId, String wxAppId, String imgSrc) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/savePuser";
		String param = "{\"businessCode\": \"f60006\", \"params\": "
				+ "{\"userName\":\"" + userName + "\",\"nickName\":\""
				+ nickName + "\",\"wxOpenId\":\"" + openId
				+ "\",\"wxAppId\":\"" + wxAppId + "\",\"imgSrc\":\"" + imgSrc
				+ "\"}}";
		// url += param;
		Integer userId = null;
		// 需要提交的json数据
		// 创建永久带参二维码
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParamPost(url,
				param);
		System.out.println("jsonObject====" + jsonObject);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				try {
					String userIdStr = jsonObject.getString("detail");
					if (userIdStr != null) {
						userId = Integer.parseInt(userIdStr);
					}
					System.out.println("存储用户:" + userName + "成功");
				} catch (Exception ex) {
					// do nothing
					System.out.println("存储用户:" + userName + "失败");
				}
			}
		}
		return userId;
	}

	public static boolean judgeAuserFenxiang(String fromOpenId,
			String toOpenId, String wxAppId) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/judgeAuserFenxiang?";
		boolean judge = false;
		String param = "param={\"businessCode\": \"f60005\", \"params\": "
				+ "{\"fromOpenId\":\"" + fromOpenId + "\",\"toOpenId\":\""
				+ toOpenId + "\",\"wxAppId\":\"" + wxAppId + "\"}}";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				try {
					String judgeStr = jsonObject.getString("detail");
					if ("1".equals(judgeStr)) {
						judge = true;
					}
				} catch (Exception ex) {
					// do nothing
					judge = false;
				}
			}
		}
		return judge;
	}

	public static void saveAuserFenxiang(String fromOpenId, String toOpenId,
			String wxAppId, String headImgUrl) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/saveAuserFenxiang";
		String param = "{\"businessCode\": \"f60004\", \"params\": "
				+ "{\"fromOpenId\":\"" + fromOpenId + "\",\"toOpenId\":\""
				+ toOpenId + "\",\"wxAppId\":\"" + wxAppId
				+ "\",\"userImg\":\"" + headImgUrl + "\"}}";

		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParamPost(url,
				param);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				try {
					System.out.println("存储用户分享表:成功");
				} catch (Exception ex) {
					// do nothing
					System.out.println("存储用户:失败");
				}
			}
		}
	}

	public static Integer getTotalFenxiang(String fromOpenId, String wxAppId) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/getTotalFenxiang?";
		Integer totalCount = 0;
		String param = "param={\"businessCode\": \"f60008\", \"params\": "
				+ "{\"fromOpenId\":\"" + fromOpenId + "\",\"wxAppId\":\""
				+ wxAppId + "\"}}";
		url += param;
		System.out.println("url======" + url);
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		System.out.println("jsonObject======" + jsonObject);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				try {
					String countStr = jsonObject.getString("detail");
					totalCount = Integer.parseInt(countStr);
				} catch (Exception ex) {
					// do nothing
				}
			}
		}
		return totalCount;
	}

	public static void main(String[] args) {
		saveWxDialog("", "a", "a", "a", "a", "a", "a", "a", "a", "a", 0, 0,
				"a", "a", "a");
		System.out.println("ok...");
	}

	public static void saveWxDialog(String toUserName, String fromUserName,
			String msgType, String wxAppId, String content, String msgId,
			String mediaId, String format, String picUrl, String thumbMediaId,
			Integer isreply, Integer isLocalSend, String title,
			String description, String userUrl) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/saveWxDialog";
		if (content == null) {
			content = "";
		}
		if (msgId == null) {
			msgId = "";
		}
		if (mediaId == null) {
			mediaId = "";
		}
		if (format == null) {
			format = "";
		}
		if (picUrl == null) {
			picUrl = "";
		}
		if (thumbMediaId == null) {
			thumbMediaId = "";
		}
		if (isreply == null) {
			isreply = 0;
		}
		if (isLocalSend != null) {
			isLocalSend = 0;
		}
		if (title != null) {
			title = "";
		}
		if (description != null) {
			description = "";
		}
		if (userUrl != null) {
			userUrl = "";
		}

		try {/*
			 * String toUserName,String fromUserName, String msgType, String
			 * wxAppId,String content,String msgId, String mediaId,String
			 * format,String picUrl,String thumbMediaId,Integer isreply,Integer
			 * isLocalSend, String title, String description, String userUrl
			 */
			String url1 = "jdbc:mysql://localhost:3306/f6db";
			String username = "shi"; // shi
			String password = "root"; // root
			try {
				Connection con = DriverManager.getConnection(url1, username,
						password);
				// wxAppId
				/*
				 * String sql=
				 * "insert into m_wx_dialog values(toUserName,fromUserName,msgType,wxAppId,content,msgId,"
				 * +
				 * "mediaId,format,picUrl,thumbMediaId,isreply,isLocalSend,title,description,userUrl)"
				 * ;
				 */
				String sql = " INSERT INTO `m_wx_dialog` (`ToUserName`,"
						+ "`FromUserName`,`MsgType`,`MsgId`,"
						+ "`MediaId`,`Format`,`PicUrl`,"
						+ "`ThumbMediaId`,`isreply`,`isLocalSend`,"
						+ "`appid`,`title`,`description`,"
						+ "`url`,content,iscollect) VALUES('"
						+ toUserName
						+ "','"
						+ fromUserName
						+ "','"
						+ msgType
						+ "','"
						+ msgId
						+ "',"
						+ "'"
						+ mediaId
						+ "','"
						+ format
						+ "','"
						+ picUrl
						+ "',"
						+ "'"
						+ thumbMediaId
						+ "',"
						+ isreply
						+ ","
						+ isLocalSend
						+ ",'"
						+ wxAppId
						+ "','"
						+ title
						+ "','"
						+ description
						+ "','"
						+ url
						+ "','"
						+ content + "'," + 1 + ")";

				PreparedStatement ps = con.prepareStatement(sql);
				int executeUpdate = ps.executeUpdate();
				
				if (executeUpdate == 1) {
					System.out.println("存储微信对话:成功");
				} else {

					System.out.println("存储微信对话:失败");
				}

			} catch (SQLException se) {
				System.out.println("数据库连接失败！");
				se.printStackTrace();
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		/*
		 * String param = "{\"businessCode\": \"f60013\", \"params\": " +
		 * "{\"toUserName\":\""
		 * +toUserName+"\",\"fromUserName\":\""+fromUserName+
		 * "\",\"msgType\":\""+msgType+"\"" +
		 * ",\"appid\":\""+wxAppId+"\",\"content\":\""
		 * +content+"\",\"msgId\":\""+msgId+"\",\"mediaId\":\""+mediaId+"\"" +
		 * ",\"format\":\""
		 * +format+"\",\"picUrl\":\""+picUrl+"\",\"thumbMediaId\":\""
		 * +thumbMediaId+"\"" +
		 * ",\"isreply\":\""+isreply+"\",\"isLocalSend\":\""
		 * +isLocalSend+"\",\"title\":\""
		 * +title+"\",\"description\":\""+description
		 * +"\",\"url\":\""+userUrl+"\"}}";
		 * 
		 * JSONObject jsonObject =
		 * JsonUtil.resolvejsonFromUrlForParamPost(url,param); if(jsonObject !=
		 * null && !jsonObject.isNullObject()){ String result = null; try{
		 * result = jsonObject.getString("result"); }catch(Exception ex){ result
		 * = null; } if(result != null && result.equals("0000")){ try{
		 * System.out.println("存储微信对话:成功"); }catch(Exception ex){ //do nothing
		 * System.out.println("存储微信对话:失败"); } }
		 */
		// }
	}

	public static void saveUserAndCar(String userName, String nickName,
			String wxOpenId, String wxAppId, String carId, String carVin,
			String carYear, String carMonth, String carBrandName,
			String carSeriesName, String carModelShort, String carModel) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/saveUserAndCar";
		String param = "{\"businessCode\": \"f60014\", \"params\": "
				+ "{\"userName\":\""
				+ userName
				+ "\",\"nickName\":\""
				+ nickName
				+ "\",\"wxOpenId\":\""
				+ wxOpenId
				+ "\",\"isWeixin\":\"1\",\"wxAppId\":\""
				+ wxAppId
				+ "\""
				+ ",\"carId\":\""
				+ carId
				+ "\",\"carVin\":\""
				+ carVin
				+ "\",\"carYear\":\""
				+ carYear
				+ "\",\"carMonth\":\""
				+ carMonth
				+ "\""
				+ ",\"carBrandName\":\""
				+ carBrandName
				+ "\",\"carSeriesName\":\""
				+ carSeriesName
				+ "\",\"carModelShort\":\""
				+ carModelShort
				+ "\""
				+ ",\"carModel\":\"" + carModel + "\"}}";

		System.out.println("saveUserAndCar param ==" + param);

		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParamPost(url,
				param);
		System.out.println("jsonObject=====" + jsonObject);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}

			if (result != null && result.equals("0000")) {
				try {
					System.out.println("存储用户与 车型信息:成功");
				} catch (Exception ex) {
					// do nothing
					System.out.println("存储用户与车辆信息:失败");
				}
			}
		}
	}

	public static String getMsgReply(String key) {
		String url = "http://op.juhe.cn/robot/index?";
		String reply = "";
		String param = "info=" + key + "&key=2981db4e3d6199d2e04d1545d5d32615";
		url += param;
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("error_code");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0")) {
				JSONObject detailObject = jsonObject.getJSONObject("result");
				if (detailObject != null) {
					try {
						reply = detailObject.getString("text");
					} catch (Exception ex) {
						// do nothing
						reply = "";
					}
				}
			}
		}
		return reply;
	}

	/*
	 * public static void main(String[] args){ //{"businessCode": "f60014",
	 * "params": {"userName":"彭松","nickName":"彭松","isWeixin":"1","wxAppId":
	 * "wxe73db62dc7c5ef3d"
	 * ,"carId":"23967","carVin":"LFMKV36F4C0126189","carYear"
	 * :"2011","carMonth":
	 * "8","carBrandName":"丰田","carSeriesName":"RAV4","carModelShort"
	 * :"丰田 RAV4","carModel":"丰田 8年8月 手动变速器(MT) 2.0"}}
	 * //saveUserAndCar(userName, nickName, wxOpenId, wxAppId, carId, carVin,
	 * carYear, carMonth, carBrandName, carSeriesName, carModelShort, carModel);
	 * String url = "http://api.f6car.com/datasrv/2.0/wxb/saveUserAndCar";
	 * String param = "{\"businessCode\": \"f60014\", \"params\": " +
	 * "{\"userName\":\"小王\",\"nickName\":\"\",\"userTel\":\"13555665656\",\"stationCode\":\"1234\",\"isWeixin\":\"0\""
	 * +
	 * ",\"birthday\":\"\",\"wxOpenId\":\"\",\"wxAppId\":\"\",\"carPrefix\":\"冀\",\"carMidFix\":\"C\""
	 * +
	 * ",\"carLastFix\":\"56566\",\"carNumber\":\"冀C56566\",\"carInsuranceDateStr\":\"\",\"carVin\":\"\""
	 * +
	 * ",\"carBrandId\":\"53\",\"factoryId\":\"188\",\"seriesId\":\"1398\",\"carYear\":\"2013\",\"carMonth\":\"11\""
	 * +
	 * ",\"carBrandName\":\"大众\",\"carSeriesName\":\"朗境\",\"carModelShort\":\"大众 朗境\""
	 * +
	 * ",\"carModel\":\"大众 朗境  2013年11月  DSG  CST 1.4 T\",\"distanceStr\":\"\",\"carId\":\"65934\"}}"
	 * ;
	 * 
	 * JSONObject jsonObject =
	 * JsonUtil.resolvejsonFromUrlForParamPost(url,param); if(jsonObject != null
	 * && !jsonObject.isNullObject()){ String result = null; try{ result =
	 * jsonObject.getString("result"); }catch(Exception ex){ result = null; }
	 * 
	 * if(result != null && result.equals("0000")){ try{
	 * System.out.println("存储用户与 车型信息:成功"); }catch(Exception ex){ //do nothing
	 * System.out.println("存储用户与车辆信息:失败"); } } }
	 * 
	 * }
	 */
	public static Fenxiang getTotalOrder(String fromOpenId, String wxAppId) {
		String url = "http://api.f6car.com/datasrv/2.0/wxb/getTotalOrder?";
		String param = "param={\"businessCode\": \"f60028\", \"params\": "
				+ "{\"fromOpenId\":\"" + fromOpenId + "\",\"wxAppId\":\""
				+ wxAppId + "\"}}";
		url += param;
		System.out.println("url======" + url);
		JSONObject jsonObject = JsonUtil.resolvejsonFromUrlForParam(url);
		System.out.println("jsonObject======" + jsonObject);
		Fenxiang fenxiang = null;
		if (jsonObject != null && !jsonObject.isNullObject()) {
			String result = null;
			try {
				result = jsonObject.getString("result");
			} catch (Exception ex) {
				result = null;
			}
			if (result != null && result.equals("0000")) {
				JSONObject detailObject = jsonObject.getJSONObject("detail");
				if (detailObject != null) {
					fenxiang = new Fenxiang();
					try {
						String fenxiangnum = detailObject
								.getString("fenxiangnum");
						fenxiang.setFenxiangnum(fenxiangnum);
					} catch (Exception ex) {
						// do nothing
					}
					try {
						String ordernum = detailObject.getString("ordernum");
						fenxiang.setOrdernum(ordernum);
					} catch (Exception ex) {
						// do nothing
					}
				}
			}
		}
		return fenxiang;
	}

}
